#!/usr/bin/env bash
set -e
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# Function :linux 二进制安装mysql
# Platform :RedHatEL7.x Based Platform
# Version  :1.01
# Date     :2023-04-06
# Author   :mugoLH
# Contact  :hxsaj@126.com
# Company  :
# depend on:
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
info_p(){  printf "\e[1;32;40m%-12s\e[0m %-1s\n\e[0m" "${1}" "${2}"  >&1 ;}
tips_p(){  printf "\e[1;36;40m%-5s\e[0m %-1s\n\e[0m"  "${1}" "${2}"  >&1 ;}
error_p(){ printf "\e[1;35;40m%-12s\e[0m %-1s\n\e[0m" "${1}" "${2}"  >&1 ;}
#  脚本引用 Import the script
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

#  变量列表 List of common variables
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

# MySQL配置模板
mysql_demo(){
	Conf_File=${1}
	install_dir=${2}
	Base_Mysql=${3}
	DB_Port=${4}
	echo -e "
[client]
default-character-set  = utf8mb4

[mysql]
port                   = ${DB_Port}
socket                 = ${install_dir}/${Base_Mysql}/data/mysql.sock
default-character-set  = utf8mb4

[mysqld]
port                   = ${DB_Port}
default_storage_engine = InnoDB
basedir                = ${install_dir}/${Base_Mysql}
datadir                = ${install_dir}/${Base_Mysql}/data
socket                 = ${install_dir}/${Base_Mysql}/data/mysql.sock
character-set-client-handshake = FALSE
character-set-server   = utf8mb4
collation-server       = utf8mb4_unicode_ci
init_connect           = 'SET NAMES utf8mb4'
max_connections        = 2000
max_allowed_packet     = 128M
innodb_file_per_table  = 1
tmp_table_size         = 134217728
max_heap_table_size    = 134217728
lower_case_table_names = 1

log-bin                = mysql-bin
max_binlog_size        = 1024M
expire_logs_days       = 1
log_slave_updates      = 1
server-id              = 1
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
" > ${Conf_File}
}


# 检查wget命令
function wget_chack(){
	if command -v wget > /dev/null ;then
		echo -e "[ 安装 wget    ]: " && yum -y -q install wget
	fi
}
# 下载 mysql 二进制文件
function wget_download(){
	Download_URL=${1}
	if [[ $(whereis wget | wc -l) -eq 1 ]];then
		echo -e "[ 下载文件     ]：" && wget -c ${Download_URL} --no-check-certificate
	else
		wget_chack
	fi
}
#  控制台
function change_opera(){
	echo -e "\n操作内容："
	tips_p 1） MySQL 部署
	tips_p 2） MySQL 查看
	tips_p 3） MySQL 用户管理
	tips_p 4） MySQL 备份恢复
	tips_p 5） MySQL 压测
	tips_p q） 退出
	read -p "选择（输入序号）：" ch_op
	case C${ch_op} in
		C1 ) mysql_install;  change_opera  ;;
		C2 ) mysql_view   ;  change_opera  ;;
		C3 ) mysql_userctl;  change_opera  ;;
		C4 ) mysql_backup ;  change_opera  ;;
		C5 ) mysql_sysbench; change_opera  ;;
		Cq ) exit		   	               ;;
		C* ) change_opera  		           ;;
	esac
}
# 安装 mysql 二进制文件
function mysql_install(){
	#  获取安装目录
	get_install_dir(){
		if [ $# -eq 1 ];then
			if [ -d ${1} ];then
				export install_dir=${1}
			else
				echo -e "[ 创建安装目录 ]：${1}"
				mkdir -p ${1}
				export install_dir=${1}
			fi
		else
			read -p "请输入安装目录：" InstallDir
			get_install_dir ${InstallDir}
		fi
	}
	#  获取安装文件或文件URL
	get_binfile_ordownload_URL(){
		if [ $# -eq 1 ];then
			if [[ -f ${1} ]];then
				export Bin_tar_file=${1}
			elif [[ $(curl -I -m 10 -o /dev/null -s -w %{http_code} ${1} ) -eq 200 ]]; then
				# 下载 mysql 二进制文件
				wget_chack
				wget_download ${1}
				# 确定下载文件的的名字
				export Bin_tar_file=$(echo "${1}" | awk -F "/" '{print$NF}')
			else
				echo -e "不是tar.gz压缩包 或 文件下载URL错误！"
				return 2
			fi
		else
			read -p "请输入文件名或文件下载URL：" FileNameOrURL
			get_binfile_ordownload_URL ${FileNameOrURL}
		fi
	}
	# 获取源代码
	get_sourecode_ordownload_URL(){
		if [ $# -eq 1 ];then
			if [[ -f ${1} ]];then
				export source_tar_file=${1}
			#elif [[ $(curl -I -m 10 -o /dev/null -s -w %{http_code} ${1} ) -eq 200 ]]; then
			#	# 下载 mysql 二进制文件
			#	wget_chack
			#	wget_download ${1}
			#	# 确定下载文件的的名字
			#	export Bin_tar_file=$(echo "${1}" | awk -F "/" '{print$NF}')
			else
				echo -e "不是tar.gz压缩包 或 文件下载URL错误！"
				return 2
			fi
		else
			read -p "请输入文件名或文件下载URL：" FileNameOrURL
			get_binfile_ordownload_URL ${FileNameOrURL}
		fi
	}
	# 
	install_dir=${1}
	BintarFile_or_DownloadURL=${2}

	if [[ $# -eq 2 ]];then

		# 解压二进制到指定目录
		echo -e "[ 解压文件 ]: ${install_dir}" && tar -zxf ${Bin_tar_file} -C ${install_dir}/

		# 修改目录名字，便于使用
		Bin_Basename=$(tar -ztf ${Bin_tar_file} | head -5 | awk -F "/" '{print$1}' |sort -nr |uniq)
		Base_Mysql=$(echo ${Bin_Basename} |awk -F "-" '{print$1"-"$2}')
		mv ${install_dir}/${Bin_Basename} ${install_dir}/${Base_Mysql}

		# 创建配置目录和数据目录
		mkdir -p ${install_dir}/${Base_Mysql}/{data,conf}

		# 生成配置文件
		echo -e "[ 生成配置 ]：${install_dir}/${Base_Mysql}/conf/my.cnf "
		mysql_demo ${install_dir}/${Base_Mysql}/conf/my.cnf ${install_dir} ${Base_Mysql} 3306

		# 创建运行账号
		if ! id mysql >/dev/null 2>&1;then
			useradd mysql
		fi

		# 授权相关目录权限
		chown -R mysql.mysql ${install_dir}

		# 写入环境变量
		echo -e "[ 环境变量 ]：/etc/bashrc"
		echo -e "export PATH=${install_dir}/${Base_Mysql}/bin:\$PATH" >> /etc/bashrc

		# 环境变量生效
		source /etc/bashrc

		# 软连接sock文件
		ln -s ${install_dir}/${Base_Mysql}/data/mysql.sock /tmp/mysql.sock

		# 初始化 mysql
		echo -e "[ 初始服务 ]:"
		mysqld --defaults-file=${install_dir}/${Base_Mysql}/conf/my.cnf --user=mysql --initialize > /tmp/${Base_Mysql}.install.tmp 2>&1

		# 启动mysql
		echo -e "[ 启动mysql ]: ${install_dir}/${Base_Mysql}/bin/mysqld_safe --defaults-file=${install_dir}/${Base_Mysql}/conf/my.cnf --user=mysql &"
		${install_dir}/${Base_Mysql}/bin/mysqld_safe --defaults-file=${install_dir}/${Base_Mysql}/conf/my.cnf --user=mysql &

		# 修改初始密码
		sleep 5
		${install_dir}/${Base_Mysql}/bin/mysql -uroot -p$(awk '/root@localhost/{print$NF}' /tmp/${Base_Mysql}.install.tmp) --connect-expired-password -sNe "set password = password('594hxs');" 2>/dev/null
		echo -e "[ 部署完成 ]: 数据库root密码：594hxs，请执行: source /etc/bashrc && mysql -uroot -p594hxs 登录数据库执行计划操作！"
	fi
}
get_
ssh_key(){

}






mysql_install(){
	# 1 单实例
    #    1.1 编译安装
    #        1.1.1 本地代码文件编译
    #        1.1.2 url下载二进制编译
    #    1.2 二进制安装
    #        1.2.1 二进制文件安装
    #        1.2.2 url下载二进制安装
    # 2 集群安装
    #    2.1 编译安装
    #    2.2 二进制按照
	# 编译安装
	# 1，二进制文件安装（本地/URL）
	# 检查wget命令
	
	



	if [ $# -eq 0 ];then
	fi
}

    #  获取主机组清单
    while [ -n "$1" ]; do
        case $1 in
            -f | --file )
                HOST_FILE="${2}"
                shift 2
                ;;
            *)
                break
                ;;
        esac
    done

